package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.BankerProductImgRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ImgUploadRequest;
import com.ytjj.qmyx.supplychain.mapper.BankerProductImgMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerProductMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerProduct;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerProductImg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BankerProductImgService {
    @Autowired
    private BankerService bankerService;
    @Resource
    private BankerProductImgMapper bankerProductImgMapper;
    @Resource
    private BankerProductMapper bankerProductMapper;

    public void addBankerProductImg(YxBankerProductImg yxBankerProductImg) {
        YxBanker userInfo = bankerService.getUserInfo();
        yxBankerProductImg.setBankerId(userInfo.getId());
        yxBankerProductImg.setCreateTime(new Date());
        bankerProductImgMapper.insertSelective(yxBankerProductImg);
    }

    @Transactional(rollbackFor = Exception.class)
    public int batchAddImg(ImgUploadRequest imgUploadRequest) {
        int count = 0;
        if (!CollectionUtils.isEmpty(imgUploadRequest.getImgUrls())) {
            for (Map<String, String> param : imgUploadRequest.getImgUrls()) {
                String name = param.get("name").substring(0, param.get("name").indexOf("."));
                Integer num = 0;
                if (imgUploadRequest.getFileType().equals("img") && !name.equals("0")) {
                    try {
                        num = Integer.parseInt(name);
                    } catch (RuntimeException e) {
                        throw new ApiException("文件名称必须为数字！");
                    }
                } else {
                    num = 1;
                }
                YxBanker userInfo = bankerService.getUserInfo();
                // banker_product_img库
                YxBankerProductImg bankerProductImg = new YxBankerProductImg();
                bankerProductImg.setImgUrl(param.get("url"));
                bankerProductImg.setBankerId(userInfo.getId());
                bankerProductImg.setProductId(imgUploadRequest.getProductId());
                bankerProductImg.setType(imgUploadRequest.getType());
                bankerProductImg.setFileType(imgUploadRequest.getFileType());
                bankerProductImg.setCreateTime(new Date());
                bankerProductImg.setSort(num);
                count = bankerProductImgMapper.insertSelective(bankerProductImg);

                // 判断信息是否完善，stepFlow状态更新
                List<YxBankerProductImg> imgList = selectBankerProductImgByExample(imgUploadRequest.getProductId(), Arrays.asList("info", "banner"));
                List<YxBankerProductImg> info = imgList.stream().filter(s -> s.getType().equals("info")).collect(Collectors.toList());
                List<YxBankerProductImg> banner = imgList.stream().filter(s -> s.getType().equals("banner")).collect(Collectors.toList());

                if (!info.isEmpty() && !banner.isEmpty()) {
                    YxBankerProduct bankerProduct = new YxBankerProduct();
                    bankerProduct.setId(imgUploadRequest.getProductId());
                    bankerProduct.setStepFlow(1);
                    bankerProductMapper.updateByPrimaryKeySelective(bankerProduct);
                }
            }
        } else {
            throw new ApiException("文件名不能为空");
        }
        return count;
    }

    private List<YxBankerProductImg> selectBankerProductImgByExample(Integer productId, List<String> types) {
        Example example = new Example(YxBankerProductImg.class);
        example.createCriteria().andEqualTo("productId", productId).andIn("type", types);
        example.orderBy("sort").asc().orderBy("createTime").desc();
        example.orderBy("sort").asc().orderBy("createTime").desc();
        List<YxBankerProductImg> imgList = bankerProductImgMapper.selectByExample(example);
        return imgList;
    }

    public CommonPage<YxBankerProductImg> getBankerProductImgList(BankerProductImgRequest bankerProductImgRequest) {
        List<YxBankerProductImg> bankerProductImgList = selectBankerProductImgByExample(bankerProductImgRequest.getProductId(), Arrays.asList(bankerProductImgRequest.getType()));
        return CommonPage.restPage(bankerProductImgList);
    }

    public void editBankerProductImg(ImgUploadRequest imgUploadRequest) {
        YxBankerProductImg yxBankerProductImg = new YxBankerProductImg();
        yxBankerProductImg.setId(imgUploadRequest.getId());
        yxBankerProductImg.setImgUrl(imgUploadRequest.getImg());
        yxBankerProductImg.setSort(imgUploadRequest.getSort());
        yxBankerProductImg.setFileType(imgUploadRequest.getFileType());
        yxBankerProductImg.setType(imgUploadRequest.getType());
        yxBankerProductImg.setUpdateTime(new Date());
        bankerProductImgMapper.updateByPrimaryKeySelective(yxBankerProductImg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteBankerProductImg(Integer id) {
        YxBankerProductImg bankerProductImg = bankerProductImgMapper.selectByPrimaryKey(id);
        bankerProductImgMapper.deleteByPrimaryKey(id);

        // 判断信息是否完善，stepFlow状态更新
        List<YxBankerProductImg> imgList = selectBankerProductImgByExample(bankerProductImg.getProductId(), Arrays.asList("info", "banner"));
        List<YxBankerProductImg> info = imgList.stream().filter(s -> s.getType().equals("info")).collect(Collectors.toList());
        List<YxBankerProductImg> banner = imgList.stream().filter(s -> s.getType().equals("banner")).collect(Collectors.toList());
        if (info.isEmpty() || banner.isEmpty()) {
            YxBankerProduct bankerProduct = new YxBankerProduct();
            bankerProduct.setId(bankerProductImg.getProductId());
            bankerProduct.setStepFlow(0);
            bankerProductMapper.updateByPrimaryKeySelective(bankerProduct);
        }
    }
}
